<template>
  <view class="note-view">
    <!-- 提示窗示例 -->
   <uni-popup ref="alertDialog" type="dialog">
     <uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="删除笔记" content="是否删除当前的笔记!" @confirm="dialogConfirm"
       @close="dialogClose"></uni-popup-dialog>
   </uni-popup>
    <scroll-view scroll-y="true" class="note-comment-box" lower-threshold="50" @scrolltolower="getMoreCmt">
      <!-- 笔记图片列表 -->
      <view>
        <swiper class="note-img-list" :indicator-dots="data.indicatorDots" display-multiple-items="1" skip-hidden-item-layout="true">
          <swiper-item class="note-view-img" v-for="(item,index) in data.note.imageList" :key="index">
            <image v-if="index==0" class="note-view-img" mode="widthFix" :src="item.url" @click="imgPreview(index)"></image>         
            <image v-else class="note-view-img" :mode="item.width>=0.89*item.height?'widthFix':'heightFix'" :src="item.url" @click="imgPreview(index)"></image>
          </swiper-item>
        </swiper>     
      </view>
      <!-- 笔记内容 -->
      <view class="note-title">
        <text user-select="true">{{data.note.title}}</text>
      </view>
      <view class="note-content">
        <text user-select="true">{{data.note.content}}</text>
      </view>
      <view class="note-time">
        <text>{{data.note.time}}</text>
      </view>
      
      <!-- 作者信息 -->
      <view class="user-box" @click="showOtherInfo(data.note.userId)">
        <image class="user-avatar" lazy-load="true" :src="data.note.authorAvatar"></image>
        <view class="user-info">
          <text class="user-name">{{data.note.authorName}}</text>
        </view>
         <button class="s-button" v-if="data.curUser != null && data.curUser.id==data.note.userId" @click="updateNote">编辑</button>
         <image class="remove-img" src="../../static/img/remove.png" v-if="data.curUser != null && data.curUser != null && data.curUser.id==data.note.userId" @click="dialogToggle"></image>
         <button class="s-button" v-else-if="data.curUser != null && data.curUser.id != data.note.userId && data.note.att > 0" @click.stop="disAttUser(data.note.userId)">已关注</button>
         <button class="s-button" v-else @click.stop="attUser(data.note.userId)">关注</button>
      </view>
      
      <view class="note-line"></view>
      <view class="comment-num">
        <text>共{{data.note.cmtNum}}条评论</text>
      </view>
      <!-- 笔记评论 -->
      <view class="comment-list">
        <view class="comment" v-for="(item,index) in data.commentList" :key="index">
          <view class="comment-info">
            <image class="comment-avatar" lazy-load="true" @click="showOtherInfo(item.userId)" :src="item.avatar"></image>
            <text class="comment-author-name">{{item.userName}}</text>
            <view class="comment-like-box" @click="likeComment(index)">
              <image v-if="item.like > 0" class="comment-like-btn" src="../../static/img/like-btn2.png"></image>
              <image v-else class="comment-like-btn" src="../../static/img/like-btn1.png"></image>
              <text class="comment-like-num">{{item.likeNum}}</text>
            </view>

          </view>
          <!-- 评论内容 -->
          <view class="comment-content">
            <text class="comment-text">{{item.content}}</text>
            <view class="comment-time">
              <text>{{item.time}}</text>
              <text @click="reply(index)">&nbsp;&nbsp;回复</text>
            </view>

          </view>       
          <!-- 回复列表 -->
          <view class="re-comment">
            <view class="comment" v-for="(item1,index1) in item.replyList" :key="index1">
              <view class="comment-info">
                <image class="re-comment-avatar" lazy-load="true" @click="showOtherInfo(item1.userId)" :src="item1.avatar"></image>
                <text class="comment-author-name">{{item1.userName}}</text>
                <view class="comment-like-box" @click="likeReply(index,index1)">
                  <image v-if="item1.like > 0" class="comment-like-btn" src="../../static/img/like-btn2.png"></image>
                  <image v-else class="comment-like-btn" src="../../static/img/like-btn1.png"></image>
                  <text class="comment-like-num">{{item1.likeNum}}</text>
                </view>
            
              </view>
              <!-- 评论内容 -->
              <view class="comment-content">
                <text v-if="item1.replyUserName != null" style="color: #949494;">回复{{item1.replyUserName}}&nbsp;</text>
                <text class="comment-text">{{item1.content}}</text>
                <view class="comment-time"> 
                  <text>{{item1.time}}</text>
                  <text @click="replyReply(index,index1)">&nbsp;&nbsp;回复</text>
                </view>
              </view>
            </view>
            <view class="more-reply" v-if="data.commentList[index].totalReply > data.commentList[index].replyList.length" @click="getMoreReply(index)">
              <text>查看更多回复</text>
            </view>  
          </view>
        </view>
        <view class="tip-tag" v-if="data.commentList == null ||data.commentList.length == 0">
          暂无内容/(ㄒoㄒ)/~~
        </view>
      </view>
    </scroll-view>
   
    <!-- 底部发表评论或点赞 -->
    <view class="comment-view" :style="{ bottom: data.bottomValue + 'px' }">
      <view style="display: flex;align-items: center;height: 100%;">
        <view class="comment-input">
          <input v-model="data.msg" class="c-input" type="text" @blur="changeFocus" @focus="inputFocus" :focus="data.focus" @confirm="sendMsg" :placeholder="data.placeholder" :adjust-position="false"/>
        </view>
          <view class="comment-icon-box">
            <view class="icon-box" @click="likeNoteBtn">
              <image v-if="data.note.like>0" class="comment-icon" src="../../static/img/like-btn2.png"></image>
              <image v-else class="comment-icon" src="../../static/img/like-btn1.png"></image>
              <text>{{data.note.likeNum}}</text>
            </view>
            <view class="icon-box" @click="starNoteBtn">
              <image v-if="data.note.star>0" class="comment-icon" src="../../static/img/star-btn2.png"></image>
              <image v-else class="comment-icon" src="../../static/img/star-btn1.png"></image>
              <text>{{data.note.starNum}}</text>
            </view>
           <view class="icon-box">
             <image class="comment-icon" src="../../static/img/comment-btn1.png"></image>
             <text>{{data.note.cmtNum}}</text>
           </view>
          </view>
        
      </view>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs } from 'vue';
import {onLoad,onUnload,onShow} from '@dcloudio/uni-app'
import helper from '../../common/helper';

const data = reactive({
  curUser: uni.getStorageSync("curUser") || null,
  noteId:'',
  index: "",
  isLike:1,
  isStar:1,
  note:{},
  msg: '',
  indicatorDots: true,
  focus: false,
  commentList:[],
  pageNum:0,
  pageSize:10,
  placeholder: "说点什么...",
  commentIndex: '',
  replyIndex: '',
  cmtFlag: 1,
  msgType:"",
  delete: 0,
  imgUrlList:[],
  totalCmt: 0,
  bottomValue: 0,
});
    
//警告窗口
const alertDialog = ref(null)

function dialogToggle(type) {
  data.msgType = type
  alertDialog.value.open()
}
    
onLoad((options)=>{
  console.log(options)
  data.noteId = options.noteId
  data.index = options.index
  data.event = options.event
})

onShow(()=>{
  if(data.noteId != ""){
    getNoteDetail()
    getComment()
    addBrowseLog()
  }
})

onUnload((options)=>{
  console.log("发起事件like")
  if(data.index != ""){
    uni.$emit('like', {
      like: data.note.like,
      index: data.index,
      event: data.event,
      delete: data.delete
    });
  }
})

function imgPreview(index) {
  uni.previewImage({
      current:index,
      urls: data.imgUrlList
  })
}

function addBrowseLog(){
  if(helper.getToken() == null){
    return
  }
  uni.request({
    url: helper.webUrl + "/note/addBrowseNoteLog",
    method:'POST',
    header:{
      "token": helper.getToken(),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: {
      noteId: data.noteId,
    },
    success: (res) => {
      console.log(res.data);
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  })
}

function changeFocus(){
  console.log("修改focus值")
  data.focus = false
  data.placeholder = "说点什么..."
  data.commentIndex= '',
  data.replyIndex= '',
  data.cmtFlag = 1
  data.bottomValue = 0
}

function inputFocus(e){
  //修改输入的盒子的bottom值
  data.bottomValue = e.detail.height
}

async function getNoteDetail(){
  let res = await helper.getNoteDetailReq(data.noteId)
  if(res.data.code == 200){
    data.note = res.data.data
    data.note.time = helper.getDateTime(data.note.time)
    if(data.note.imageList.length <= 1){
      data.indicatorDots = false
    }
    for(let i = 0; i < data.note.imageList.length; i++){
       data.imgUrlList.push(data.note.imageList[i].url)
    }
  }
}

function showOtherInfo(userId){
  console.log("查看用户")
  if(data.curUser != null && userId == data.curUser.id){
    return
  }
  uni.navigateTo({
    url:"/subpages/otherInfo/otherInfo?userId="+userId
  })
}

async function attUser(userId){
  if(data.curUser == null){
    return
  }
  console.log("关注用户")
  let res = await helper.attUserReq(userId)
  if(res.data.code == 200){
    data.note.att = 1
  }
}

async function disAttUser(userId){
  if(data.curUser == null){
    return
  }
  let res = await helper.disAttUserReq(userId)
  if(res.data.code == 200){
    data.note.att = 0
  }
}

function getMoreCmt(){
  if(data.totalCmt <= data.commentList.length){
    return
  }
  getComment()
}

function getComment(){
  uni.request({
    url: helper.webUrl + "/comment/getCmtByNoteId",
    header:{
      "token": helper.getToken()
    },
    data: {
      noteId: data.noteId,
      pageNum: data.pageNum,
      pageSize: data.pageSize
    },
    success: (res) => {
      console.log(res.data);
      if(res.data.code == 200 && res.data.data != null){
        data.pageNum++
        data.commentList = res.data.data.record
        data.totalCmt = res.data.data.total
        for(let i = 0; i < data.commentList.length; i++){
          data.commentList[i].time = helper.getDateTime(data.commentList[i].time)
          for(let j = 0; j < data.commentList[i].replyList.length; j++){
            data.commentList[i].replyList[j].time = helper.getDateTime(data.commentList[i].replyList[j].time)
          }
        }
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  })
}

function getMoreReply(index){
  let commentId = data.commentList[index].id 
  let len = data.commentList[index].replyList.length
  console.log("查看更多"+commentId+" "+len)
  uni.request({
      url: helper.webUrl + "/reply/getReplyByCmtId",
      method:'GET',
      data: {
        commentId: commentId,
        pageNum: len,
        pageSize: 5
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200 && res.data.data != null){
          let replyList = res.data.data.record
          data.commentList[index].totalReply = res.data.data.total
          for(let i = 0; i < replyList.length; i++){
            replyList[i].time = helper.getDateTime(replyList[i].time)
            data.commentList[index].replyList.push(replyList[i])
          }        
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
}

async function likeNoteBtn(){
  if(helper.getUserId() == null){
    return;
  }
  if(data.note.like > 0){
    let res = await helper.dislikeNoteReq(data.noteId)
    if(res.data.code == 200){
      data.note.like = 0
      data.note.likeNum--
    }
  }else{
    let res = await helper.likeNoteReq(data.noteId)
    if(res.data.code == 200){
      data.note.like = 1
      data.note.likeNum++
    }
  }
}

async function starNoteBtn(){
  if(helper.getUserId() == null){
    return;
  }
  if(data.note.star > 0){
    let res = await helper.disStarNoteReq(data.noteId)
    if(res.data.code == 200){
      data.note.star = 0
      data.note.starNum--
    }
  }else{
    let res = await helper.starNoteReq(data.noteId)
    if(res.data.code == 200){
      data.note.star = 1
      data.note.starNum++
    }
  }
}


function addCmtReq(msg){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/comment/addCmt",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: helper.getUserId(),
        noteId: data.noteId,
        content: msg
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
}

function sendMsg(){
  console.log("发送信息"+data.commentIndex+" "+data.replyIndex)
  if(data.curUser == null){
    return
  }
  if(data.msg == null || data.msg.trim() == ''){
    return
  }
  if(data.cmtFlag == 1){
    console.log("发送评论")
    addCmt()
  }else{
    console.log("发送回复")
    replyComment()
  }
}

async function addCmt(){
  console.log("发表评论"+data.msg)
  let res = await addCmtReq(data.msg)
  console.log(res)
  if(res.data.code == 200){
    //添加到首位
    let cmt =  res.data.data
    cmt.avatar = data.curUser.avatar
    cmt.userName = data.curUser.userName
    cmt.time = helper.getDateTime(cmt.time)
    cmt.like = 0
    cmt.likeNum = 0
    cmt.replyList = []
    data.commentList.unshift(cmt)
    data.msg = ''
  }
}

function replyCmtReq(commentId,msg,replyId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/reply/addReply",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: helper.getUserId(),
        commentId: commentId,
        content: msg,
        replyId: replyId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });  
}

function reply(index){
  console.log("回复评论"+index)
  data.focus = true
  data.msg = ''
  data.placeholder = "回复： "+data.commentList[index].userName+" "
  data.commentIndex = index
  data.replyIndex = '',
  data.cmtFlag = 2
}

async function replyComment(){
  let commentIndex = data.commentIndex
  let replyIndex = data.replyIndex
  let commentId = data.commentList[commentIndex].id
  let replyId = ''
  let cmtFlag = data.cmtFlag
  if(cmtFlag == 3){
    replyId = data.commentList[commentIndex].replyList[replyIndex].id
  }
  let res = await replyCmtReq(commentId,data.msg,replyId)
  if(res.data.code == 200){
    //添加到首位
    let reply =  res.data.data
    reply.avatar = data.curUser.avatar
    reply.userName = data.curUser.userName
    reply.time = helper.getDateTime(reply.time)
    reply.like = 0
    reply.likeNum = 0
    if(cmtFlag == 3){
      reply.replyUserName = data.commentList[commentIndex].replyList[replyIndex].userName
    }
    data.commentList[commentIndex].replyList.unshift(reply)
    data.msg = ''
  }
}
function replyReply(cIndex,rIndex){
  console.log("回复的回复"+cIndex)
  console.log(rIndex)
  data.focus = true
  data.placeholder = "回复： "+data.commentList[cIndex].replyList[rIndex].userName+" "
  data.commentIndex = cIndex
  data.replyIndex = rIndex
  data.cmtFlag = 3
}

async function likeComment(cIndex){
  if(helper.getUserId() == null){
    return;
  }
  console.log("点赞评论"+cIndex)
  if(data.commentList[cIndex].like > 0){
    let res = await helper.dislikeCmtReq(data.commentList[cIndex].id)
    if(res.data.code == 200){
      data.commentList[cIndex].like = 0
      data.commentList[cIndex].likeNum--
    }
  }else{
    let res = await helper.likeCmtReq(data.commentList[cIndex].id)
    if(res.data.code == 200){
      data.commentList[cIndex].like = 1
      data.commentList[cIndex].likeNum++
    }
  }  
}

async function likeReply(cIndex,rIndex){
  if(helper.getUserId() == null){
    return;
  }
  console.log("点赞回复"+cIndex+" "+rIndex)
  if(data.commentList[cIndex].replyList[rIndex].like > 0){
    let res = await helper.dislikeReplyReq(data.commentList[cIndex].replyList[rIndex].id)
    if(res.data.code == 200){
      data.commentList[cIndex].replyList[rIndex].like = 0
      data.commentList[cIndex].replyList[rIndex].likeNum--
    }
  }else{
    let res = await helper.likeReplyReq(data.commentList[cIndex].replyList[rIndex].id)
    if(res.data.code == 200){
      data.commentList[cIndex].replyList[rIndex].like = 1
      data.commentList[cIndex].replyList[rIndex].likeNum++
    }
  }  
}

function dialogConfirm() {
  console.log('点击确认')
  //跳转验证验证码
  deleteNote()
}

async function deleteNote(){
  let res = await helper.deleteNoteReq(data.noteId)
   if(res.data.code == 200){
     data.delete = 1
     uni.navigateBack()
   }
}

function updateNote(){
  uni.navigateTo({
    url:"/subpages/publish/publish?noteId="+data.noteId
  })
}
</script>

<style>
.note-view{
  width: 100vw;
  height: 93vh;
}
.note-img-list{
  width: 100vw;
  min-height: 55vh;
  max-height: 60vh;
}
.note-view-img{
  width: 100vw;
  max-height: 60vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.note-comment-box{
  width: 100vw;
  height: 93vh;
}
.note-title{
  display: flex;
  max-width: 90%;
  padding: 10px;
  font-size: 18px;
}
.note-content{
  display: flex;
  max-width: 100%;
  padding: 8px;
  font-size: 16px;
}
.note-content-text{
  /* 换行 */
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.note-time,.comment-num{
  color: #6f6f6f;
  margin: 10px;
}
.note-line{
  width: 95vw;
  display: flex;
  margin: auto;
  border-top: 1px solid #c5c5c5;
}
.user-box{
  width: 100vw;
  height: 7vh;
  background-color: #fff;
  padding: 5px;
  display: flex;
  align-items: center;
}
.user-avatar{
  width: 45px;
  height: 45px;
  border-radius: 50%;
}
.user-info{
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  width: 60%;
}
.user-name{
  font-size: 16px;
  font-weight: bold;
}
.s-button{
  width: 18vw;
  height: 65%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 14px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.remove-img{
  padding: 5px;
  width: 40px;
  height: 40px;
}
.comment-list{
  padding-bottom: 15px;
}
.comment{
  display: flex;
  flex-direction: column;
}
.comment-info{
  display: flex;
  align-items: center;
  padding: 7px;
}
.comment-avatar{
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.comment-author-name{
  font-size: 15px;
  margin-left: 5px;
  color: #6f6f6f;
}
.comment-time{
  color: #6f6f6f;
  font-size: 12px;
}
.comment-like-box{
  display: flex;
  flex-direction: column;
  margin-left: auto;
  padding: 5px;
}
.comment-like-btn{
  width: 25px;
  height: 25px;
}
.comment-like-num{
  font-size: 10px;
  display: flex;
  color: #5e5e5e;
  justify-content: center;
}
.comment-content{
  width: 80%;
  font-size: 14px;
  padding-inline: 10%;
}
.comment-text{
  /* 换行 */
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.re-comment{
  padding-left: 8%;
}
.re-comment-avatar{
  width: 35px;
  height: 35px;
  border-radius: 50%;
}
.more-reply{
  color: #002444;
  margin-left: 35px;
  margin-top: 7px;
}
.comment-view{
  position: absolute;
  bottom: 0;
  align-items: center;
  width: 100vw;
  height: 7vh;
  border-top: 1px solid #aaaaaa;
  background-color: #fff;
}
.comment-input{
  width: 60%;
  height: 60%;
  margin: auto;
  display: flex;
  border-radius: 15px;
  background-color: #f4f4f4;
}
.c-input{
  margin-left: 5%;
  width: 100%;
  height: 100%;
  font-size: 14px;
}
.comment-icon-box{
  display: flex;
  margin-left: 3px;
  padding: 3px;
}
.icon-box{
  display: flex;
  justify-content: center;
  align-items: center;
}
.comment-icon{
  width: 35px;
  height: 35px;
  margin-inline: 3px;
}
</style>
